package org.grapes.wine.api.server.core;

import java.io.IOException;
import java.io.InputStream;
import java.sql.Clob;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.SQLXML;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.grapes.wine.api.exception.ErrorCode;
import org.grapes.wine.api.exception.WineException;
import org.grapes.wine.api.server.database.DerbyConfig;
import org.grapes.wine.api.server.param.MethodConfig;

public class ReadData {

	public ReadData() {
	}

	public List<Map> readTable() throws Exception {
		Connection conn = null;
		String embeddedDriver = "org.apache.derby.jdbc.EmbeddedDriver";
		String user = DerbyConfig.user;
		String password = DerbyConfig.password;
		String embeddedURL = "jdbc:derby:wineDB;user=" + user + ";password="
				+ password + ";";
		Class.forName(embeddedDriver);
		conn = DriverManager.getConnection(embeddedURL);
		Statement stmt = conn.createStatement();
		
		List<Map> list;
		list = getMethod(stmt);

		conn.close();
		return list;
	}

	private List<Map> getMethod(Statement stmt) throws SQLException, IOException {
		List list = new ArrayList();
		list.add("userId");
		list.add("name");
		list.add("email");
		List<Map> dataList = selectUser(stmt, list);

		return dataList;
	}

	private List<Map> selectUser(Statement stmt, List demandedList)
			throws SQLException, IOException {
		List<Map> result = new ArrayList<Map>();
		
		List<String> params = new ArrayList<String>();
		params.add("test");
		String query = callStatement(MethodConfig.getUser, params);
		ResultSet resultSet = null;
		Map dataMap = new HashMap();
		if (stmt.execute(query)) {
			resultSet = stmt.getResultSet();
			while (resultSet.next()) {
				dataMap = getList(resultSet, demandedList);
				result.add(dataMap);
			}
		}
		resultSet.close();
		return result;
	}
	
	private Map getList(ResultSet rs, List<String> demandedList)
			throws SQLException {
		Map dataMap = new HashMap();
		Iterator<String> it = demandedList.listIterator();
		while (it.hasNext()) {
			String obj = it.next();
			dataMap.put(obj, rs.getString(obj));
		}
		return dataMap;
	}

	private String callStatement(String methodName, List<String> params) {
		String call = null;
		StringBuffer var = new StringBuffer();
		for (String param : params) {
			var.append("'");
			var.append(param);
			var.append("',");
		}
		call = "call " + methodName + "("
				+ var.substring(0, var.length() - 1).toString() + ")";
		return call;
	}
}